﻿using MediatR;
using Microsoft.AspNetCore.Components.Forms;
using S.ReportForms.Domain.Dto;
using S.ReportForms.Infrastructure.Interface;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using static S.ReportForms.Read.API.Application.Command.BreadMatchingCountCommand;

namespace S.ReportForms.Read.API.Application.CommandHandlers
{
    /// <summary>
    /// 种母配怀统计报表
    /// </summary>
    public class BreadMatchingCountCommandHandler : IRequestHandler<EstimatedDeliveryCommand, EstimatedDeliveryDto>,IRequestHandler<BreedingDeliveryRateCommand,List<BreedingDeliveryRateDto>>,IRequestHandler<BreedingMothersStateCommand,GetBreedingMothersStateDto>
    {
        #region 注入
        private readonly IBreadMatchingRepository repository;
        public BreadMatchingCountCommandHandler(IBreadMatchingRepository repository)
        {
            this.repository = repository;
        }
        #endregion


        /// <summary>
        /// 预估分娩率
        /// </summary>
        public async Task<EstimatedDeliveryDto> Handle(EstimatedDeliveryCommand request, CancellationToken cancellationToken)
        {
            #region 获取一年中的第几周
            DateTime now = DateTime.Parse(request.BreedingDate);
            int weekNumber = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                now,
                CalendarWeekRule.FirstDay,
                DayOfWeek.Monday // 根据中国常用的公历，将周起始日设为 Monday
            );
            int year = now.Year;
            string result = string.Concat(year, weekNumber.ToString("D2"));//这是传过来数据年的哪一周
            #endregion
            // 假设输入的日期字符串格式为 "yyyy-MM-dd"
            DateTime date = DateTime.ParseExact(request.BreedingDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);

            int daysToMonday = ((int)date.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7;
            DateTime monday = date.AddDays(-daysToMonday);//星期一的日期字符串
            DateTime sunday = monday.AddDays(6);//星期日的日期字符串
            //生成查询的数据
            List<DateTime> dates = new List<DateTime>(); // 创建一个空的日期列表
            // 将初始的monday和sunday加入列表
            dates.Add(monday);
            dates.Add(sunday);

            for (int i = 1; i <=19; i++)
            {
                DateTime futureMonday = monday.AddDays(7*i);//未来 19 周后的周一的日期字符串
                DateTime futureSunday = futureMonday.AddDays(6);//未来 19 周后的周日的日期字符串

                #region 获取一年中的第几周
                now = DateTime.Parse(futureMonday.ToString());
                weekNumber = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                    now,
                    CalendarWeekRule.FirstDay,
                    DayOfWeek.Monday // 根据中国常用的公历，将周起始日设为 Monday
                );
                year = now.Year;
                //result = string.Concat(year, weekNumber.ToString("D2"));//这是传过来数据年的哪一周
                #endregion
                // 将未来周的日期加入列表
                dates.Add(futureMonday);
                dates.Add(futureSunday);
            }
            //配种数量和十九周的数量
            List<NumberOfMatings> numberOfMatings= await repository.GetBreadMatching(dates);

            //配种周次转换为string
            string formattedDate1 = monday.ToString("MM-dd");
            string formattedDate2 = sunday.ToString("MM-dd");

            //实际分娩数量
            List<int> deliverytrue = await repository.GetDeliveryDate(dates);
            int delivery = deliverytrue[0];
            //获取配种数量
            List<int> breedingCountList=await repository.GetBreedingDate(dates);
            int breedingCount = breedingCountList[0];
            EstimatedDeliveryDto estimatedDeliveryDtos = new EstimatedDeliveryDto
            {
                WeekCount = result,//周次
                BreedingDate = $"{formattedDate1}-{formattedDate2}",//配种日期   区间
                BreedingCount= breedingCount,//配种数量
                NumberOfMatingsList = numberOfMatings,//统计的数据
                EstimatedDeliveryRates = Math.Round((double)delivery / breedingCount * 100, 2),   //预估分娩率%
                DeliveryTrue = delivery,  //实际分娩
                DeliveryRate = Math.Round((double)delivery / breedingCount * 100, 2),   //分娩率%
            };

            return estimatedDeliveryDtos;
        }

        /// <summary>
        /// 配种分娩率
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<BreedingDeliveryRateDto>> Handle(BreedingDeliveryRateCommand request, CancellationToken cancellationToken)
        {
            DateTime startDate = new DateTime(request.SelectYear, 1, 1);
            DateTime endDate = new DateTime(request.SelectYear, 12, 31);

            return await repository.GetBreedingDeliveryRate(request.SelectYear, startDate, endDate);
        }

        /// <summary>
        /// 种母状态分布
        /// </summary>
        public async Task<GetBreedingMothersStateDto> Handle(BreedingMothersStateCommand request, CancellationToken cancellationToken)
        {
            //繁殖状态
            List<ReproductiveStateCount> reproductiveStateCountList = await repository.GetReproductiveState(request.VarietyId);

            //妊娠前、中、后期、临产，超预产期
            List<PregnancyCount> pregnancyCountList = await repository.GetPregnancyCountDto();

            //妊检未检
            List<PregnancyNotCount> pregnancyNotCountList = await repository.GetPregnancyNotCountDto();

            return new GetBreedingMothersStateDto
            {
                ReproductiveStateList = reproductiveStateCountList,
                PregnancyList = pregnancyCountList,
                PregnancyNotList = pregnancyNotCountList
            };
        }
    }
}
